package com.example.myfoodrecipe.fragments.recipe.adapter

import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.myfoodrecipe.databinding.TypeItemBinding

class TypeAdapter: RecyclerView.Adapter<TypeAdapter.ItemViewHolder>() {
    //list for ItemViewHolder
    val typeList = listOf("main course",
            "side dish",
            "dessert",
            "appetizer",
            "salad",
            "bread",
            "breakfast",
            "soup",
            "beverage",
            "sauce",
            "marinade",
            "fingerfood",
            "snack",
            "drink")

    //事件回调lambda(for RecipeFragment)
    lateinit var callBack: ((current:Int,last:Int)->Unit)
    //上个被选择的item
    private var lastSelected = 0

    class ItemViewHolder(binding: TypeItemBinding): RecyclerView.ViewHolder(binding.root){
        val titleTextView: TextView = binding.titleText

        //设置选中状态
         fun changeSelectedState(state: Boolean){
            titleTextView.isSelected = state
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemViewHolder {
        val adapterLayout = LayoutInflater.from(parent.context)
        return ItemViewHolder(TypeItemBinding.inflate(adapterLayout))
    }

    override fun onBindViewHolder(holder: ItemViewHolder, position: Int) {
        val item = typeList[position]
        holder.titleTextView.text = item

        //如果position为lastSelected则设为选中状态（即一进入主页面将第一个item选中）
        holder.titleTextView.isSelected = position == lastSelected

        //item被点击后更改callBack以供RecipeFragment更改当前和之前item状态
        holder.titleTextView.setOnClickListener {
            callBack(position,lastSelected)
            lastSelected = position
        }
    }

    override fun getItemCount(): Int {
        return typeList.size
    }


}